﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using AttachReminderAddIn.Properties;
using Outlook = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;
using System.IO;
using System.IO.IsolatedStorage;

namespace AttachReminderAddIn
{
    public partial class ThisAddIn
    {
        private void ThisAddIn_Startup(object sender, EventArgs e)
        {
            // Register event listener.
            Application.ItemSend += Application_ItemSend;
        }

        static void Application_ItemSend(object Item, ref bool Cancel)
        {
            // Try to cast as mail item, if cast fails it is not mail.
            var mailItem = Item as Outlook.MailItem;

            // Return if this is not mail, or if there are already attachments.
            if ((mailItem == null) || (mailItem.Attachments.Count != 0)) return;

            var lowerCaseBody = mailItem.Body.ToLower();

            var iEndOfOrigText = lowerCaseBody.IndexOf("from:");

            if (iEndOfOrigText > -1)
                lowerCaseBody = lowerCaseBody.Substring(0, iEndOfOrigText);

            // If any search terms are found in body, display confirmation message.
            var searchTermHit =
                SearchTermManager.SearchTerms.FirstOrDefault(
                    searchTerm => lowerCaseBody.Contains(searchTerm.ToLower()));

            if (searchTermHit == null) return;

            // Get original casing of hit for display in confirmation message.
            var hitIndex = lowerCaseBody.IndexOf(searchTermHit.ToLower());
            var casedHit = mailItem.Body.Substring(hitIndex, searchTermHit.Length);

            var confirmSendMsg = string.Format(Resources.ConfirmSendMsgFmt, casedHit);
            Cancel = MessageBox.Show(confirmSendMsg, Resources.ConfirmCaption, MessageBoxButtons.OKCancel) ==
                     DialogResult.Cancel;
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
            // Remove event listener.
            Application.ItemSend -= Application_ItemSend;
        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }
        
        #endregion
    }
}
